import { execute } from "../../database/connector";

import { UserQueries } from "../queries/user.query";
import { IUser } from "../../models/user.model";

/**
 * gets active user
 */
export const getUsers = async () => {
  return execute<IUser[]>(UserQueries.GetUsers, []);
};

/**
 * gets a user based on id provided
 */
export const getUserById = async (id: IUser['id']) => {
  return execute<IUser>(UserQueries.GetUserById, [id]);
};

/**
 * gets a user based on email provided
 */
export const getUserByEmployeeId = async (employeeId: IUser['employeeId']) => {
  return execute<IUser[]>(UserQueries.GetUserByEmployeeId, [employeeId]);
};

/**
 * gets a user based on login token provided
 */
export const getUserByToken = async (userToken: IUser['userToken']) => {
  return execute<IUser[]>(UserQueries.GetUserByToken, [userToken]);
};


/**
 * adds a new active user record
 */
export const insertUser = async (user: IUser) => {
  const result = await execute<{
      insertId: Promise<any>;
      affectedRows: number }>(UserQueries.AddUser, [
    [Object.values(user)]
  ]);
    console.log('result', result.insertId)
    // 返回最新插入得id
    return result.affectedRows > 0 ? result.insertId : false
};

/**
 * updates user information based on the id provided
 */
export const updateUser = async (user: IUser) => {
  const result = await execute<{
      affectedRows: number }>(UserQueries.UpdateUserById, [user, user.id]);
  return result.affectedRows > 0
};

/**
 * updates user information based on the id provided
 */
 export const deleteUser = async (id: IUser['id']) => {
  const result = await execute<{ affectedRows: number }>(UserQueries.DeleteUserById, [
    id
  ]);
  return result.affectedRows > 0;
};